<?php

namespace app\controllers;

use Yii;
use app\models\Patient;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\commands\Service;
use app\models\Comeway;
use app\models\Department;
use app\models\Disease;
use app\models\Doctor;
use app\models\Communication;
use app\commands\Mytools;
use app\models\Job;
use app\models\Patientpower;
use app\models\Sysconfig;
use app\models\User;
use app\models\Workgroup;

/**
 * PatientController implements the CRUD actions for Patient model.
 */
class PatientController extends Service
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    private function search($where, $search_condition_var, $order = '')
    {
        if ($search_condition_var != null && count($search_condition_var) > 0) {
            $where = '(' . $where . ')';
            foreach ($search_condition_var as $k => $v) {
                if (in_array($k, ['name', 'telphone', 'forever_id', 'order_number', 'wechat', 'qq', 'keyword', 'condition_log', 'talk_log']) && !empty($v)) {
                    $where .= " and {$k} like '%{$v}%'";
                }
                if (in_array($k, ['sex', 'age', 'disease_ids', 'workgroup', 'istoday', 'department_id', 'communication_id', 'comeway_id', 'user_id', 'operate_doctor_id', 'status']) && !empty($v)) {
                    $where .= " and {$k} = '{$v}'";
                }
                if (in_array($k, ['createtime', 'order_time', 'arrive_time']) && !empty($v)) {
                    $time_start = substr($v, 0, 10) . ' 00:00:00';
                    $time_end = substr($v, 13, 10) . ' 23:59:59';
                    $where .= " and {$k} between '{$time_start}' and '{$time_end}'";
                }
            }
        }

        $patient_list = Patient::find()->where($where)->orderBy($order);

        return $patient_list;
    }

    public function actionReceive()
    {
        $search_condition_var = Yii::$app->request->post('search');

        $search_condition_var = Yii::$app->request->post('search');
        if (null == $search_condition_var || count($search_condition_var) < 1) {
            $search_condition_var = Yii::$app->request->get('search');
            if (null != $search_condition_var && count($search_condition_var) > 0) {
                foreach ($search_condition_var as $key => $value) {
                    switch ($value) {
                        case 'tomorrow':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('+1 day')) . ' - ' . date('Y-m-d', strtotime('+1 day'));
                            break;
                        case 'today':
                            $search_condition_var[$key] = date('Y-m-d') . ' - ' . date('Y-m-d');
                            break;
                        case 'yestoday':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('-1 day')) . ' - ' . date('Y-m-d', strtotime('-1 day'));
                            break;
                    }
                }
            }
        }

        $workgroup_array = Workgroup::getTreeData('', $search_condition_var['workgroup']);
        $comeway_array = Comeway::getTreeData('', $search_condition_var['comeway_id']);
        $communication_array = Communication::getTreeData('', $search_condition_var['communication_id']);
        $disease_array = Disease::second_floor_key_value('', $search_condition_var['disease_ids']);
        $doctor_array = Doctor::getTreeData('', $search_condition_var['operate_doctor_id']);
        $status_array = ['未回访', '已回访', '确认到院', '已改约', '流失'];

        if (Patientpower::get_var_value('user_id') != '可修改' && Yii::$app->user->identity->jobname != '超级管理员') {
            $user_array = User::getTreeData("", Yii::$app->user->getId(), true);
        } else {
            $user_array = User::getTreeData();
        }

        $order_default = "order_time desc, createtime desc, arrive_time asc";

        $dataProvider = new ActiveDataProvider([
            'query' => $this->search("1", $search_condition_var, $order_default),
            'pagination' => array('pageSize' => 15)
        ]);

        return $this->render('receive', [
            'dataProvider' => $dataProvider,
            'search' => $search_condition_var,
            'workgroup_array' => $workgroup_array,
            'comeway_array' => $comeway_array,
            'communication_array' => $communication_array,
            'user_array' => $user_array,
            'disease_array' => $disease_array,
            'doctor_array' => $doctor_array,
            'status_array' => $status_array
        ]);
    }

    /**
     * Lists all Patient models.
     * @return mixed
     */
    public function actionIndex()
    {

        $search_condition_var = Yii::$app->request->post('search');
        if (null == $search_condition_var || count($search_condition_var) < 1) {
            $search_condition_var = Yii::$app->request->get('search');
            if (null != $search_condition_var && count($search_condition_var) > 0) {
                foreach ($search_condition_var as $key => $value) {
                    switch ($value) {
                        case 'tomorrow':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('+1 day')) . ' - ' . date('Y-m-d', strtotime('+1 day'));
                            break;
                        case 'today':
                            $search_condition_var[$key] = date('Y-m-d') . ' - ' . date('Y-m-d');
                            break;
                        case 'yestoday':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('-1 day')) . ' - ' . date('Y-m-d', strtotime('-1 day'));
                            break;
                    }
                }
            }
        }

        $workgroup_array = Workgroup::getTreeData('', $search_condition_var['workgroup']);
        $comeway_array = Comeway::getTreeData('', $search_condition_var['comeway_id']);
        $communication_array = Communication::getTreeData('', $search_condition_var['communication_id']);
        $disease_array = Disease::second_floor_key_value('', $search_condition_var['disease_ids']);
        $doctor_array = Doctor::getTreeData('', $search_condition_var['operate_doctor_id']);
        $status_array = ['未回访', '已回访', '确认到院', '已改约', '流失'];

        if (Patientpower::get_var_value('user_id') != '可修改' && Yii::$app->user->identity->jobname != '超级管理员') {
            $user_array = User::getTreeData("", Yii::$app->user->getId(), true);
        } else {
            $user_array = User::getTreeData();
        }

        $where_default = "order_time >'2010-01-01'" . " and department_id = " . Yii::$app->user->identity->department_id;

        $dataProvider = new ActiveDataProvider([
            'query' => $this->search($where_default, $search_condition_var, "order_time desc"),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'search' => $search_condition_var,
            'workgroup_array' => $workgroup_array,
            'comeway_array' => $comeway_array,
            'communication_array' => $communication_array,
            'user_array' => $user_array,
            'disease_array' => $disease_array,
            'doctor_array' => $doctor_array,
            'status_array' => $status_array
        ]);
    }

    public function actionIndexrecord()
    {
        $search_condition_var = Yii::$app->request->post('search');
        if (null == $search_condition_var || count($search_condition_var) < 1) {
            $search_condition_var = Yii::$app->request->get('search');
            if (null != $search_condition_var && count($search_condition_var) > 0) {
                foreach ($search_condition_var as $key => $value) {
                    switch ($value) {
                        case 'tomorrow':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('+1 day')) . ' - ' . date('Y-m-d', strtotime('+1 day'));
                            break;
                        case 'today':
                            $search_condition_var[$key] = date('Y-m-d') . ' - ' . date('Y-m-d');
                            break;
                        case 'yestoday':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('-1 day')) . ' - ' . date('Y-m-d', strtotime('-1 day'));
                            break;
                    }
                }
            }
        }

        $workgroup_array = Workgroup::getTreeData('', $search_condition_var['workgroup']);
        $comeway_array = Comeway::getTreeData('', $search_condition_var['comeway_id']);
        $communication_array = Communication::getTreeData('', $search_condition_var['communication_id']);
        $disease_array = Disease::second_floor_key_value('', $search_condition_var['disease_ids']);
        $doctor_array = Doctor::getTreeData('', $search_condition_var['operate_doctor_id']);
        $status_array = ['未回访', '已回访', '确认到院', '已改约', '流失'];

        if (Patientpower::get_var_value('user_id') != '可修改' && Yii::$app->user->identity->jobname != '超级管理员') {
            $user_array = User::getTreeData("", Yii::$app->user->getId(), true);
        } else {
            $user_array = User::getTreeData();
        }

        $where_default = "(order_time <'2000-01-01' or order_time is null or order_time = '')" . " and department_id = " . Yii::$app->user->identity->department_id;
        $dataProvider = new ActiveDataProvider([
            'query' => $this->search($where_default, $search_condition_var),
        ]);

        return $this->render('index_record', [
            'dataProvider' => $dataProvider,
            'search' => $search_condition_var,
            'workgroup_array' => $workgroup_array,
            'comeway_array' => $comeway_array,
            'communication_array' => $communication_array,
            'user_array' => $user_array,
            'disease_array' => $disease_array,
            'doctor_array' => $doctor_array,
            'status_array' => $status_array
        ]);
    }

    /**
     * Displays a single Patient model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    private function get_address_tree($address = '')
    {
        $address_array = [0 => '贵州省', 1 => '贵阳市', 2 => '云岩区'];
        if ($address != '') {
            $address_array = explode('-', $address);
        }
        return $address_array;
    }

    private function init_create()
    {
        $var = Mytools::array_value_trim(Yii::$app->request->post('patient'));

        $model = new Patient();
        $model->order_number = Yii::$app->user->identity->ordernumber;
        if (null != $var && count($var) > 0) {
            $var['istoday'] = $var['istoday'] == '是' ? '是' : '否';
            $model->last_recall_time = $model->createtime = date('Y-m-d H:i:s');
            $model->user_id = $var['user_id'] ? $var['user_id'] : Yii::$app->user->getId();
            $model->status = '未回访';
            $model->edit_log = Yii::$app->user->identity->showname . " 于" . $model->createtime . '创建了患者 ' . $model->name . ' 的预约单；<br />';
            $model->name = $var['name'];
            $model->sex = $var['sex'];
            $model->telphone = $var['telphone'];
            $model->istoday = $var['istoday'];
            $model->workgroup = $var['workgroup'];
            $model->forever_id = $var['forever_id'];
            $model->order_time = $var['order_time'];
            $model->age = $var['age'];
            $model->order_number = $var['order_number'];
            $model->wechat = $var['wechat'];
            $model->qq = $var['qq'];
            $model->address = $var['address'];
            $model->keyword = $var['keyword'];
            $model->department_id = $var['department_id'];
            $model->disease_ids = $var['disease_ids'];
            $model->comeway_id = $var['comeway_id'];
            $model->communication_id = $var['communication_id'];
            $model->order_doctor_id = $var['order_doctor_id'];
            $model->condition_log = $var['condition_log'];
            $model->talk_log = $var['talk_log'];

            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        $comeway_array = Comeway::getTreeData("status = '显示'", 1); //默认选择 百度竞价
        $communication_array = Communication::getTreeData("status = '显示'", 1); //默认选择 商务通咨询
        $department_array = Department::getTreeData("status = '显示'", Yii::$app->user->identity->department_id); //默认选择 用户的所属的科室
        foreach ($department_array as $index => $d) {
            $department_array[$index]['disease_array'] = Disease::getTreeData("status = '显示' and id in ({$d['disease_ids']})", $model->disease_ids);
            if (Patientpower::get_var_value('order_doctor_id') == '显示' || Yii::$app->user->identity->jobname == '超级管理员') {
                $department_array[$index]['doctor_array'] = Doctor::getTreeData("status = '显示' and id in ({$d['doctor_ids']})", $model->order_doctor_id);
            } else {
                $department_array[$index]['doctor_array'] = [];
            }
        }
        $workgroup_array = Workgroup::getTreeData('', Yii::$app->user->identity->workgroup);
        $address_array = $this->get_address_tree();

        if (Yii::$app->user->identity->jobModel->check_patient_power('修改患者归属') == '可修改' || Yii::$app->user->identity->jobModel->check_patient_power('修改患者归属') == 'super') {
            $user_array = User::getTreeData("status = '在职'", Yii::$app->user->getId());
        } else {
            $user_array = User::getTreeData("status = '在职'", Yii::$app->user->getId(), true);
        }

        $view_list = [
            'model' => $model,
            'comeway_array' => $comeway_array,
            'communication_array' => $communication_array,
            'department_array' => $department_array,
            'workgroup_array' => $workgroup_array,
            'address_array' => $address_array,
            'user_array' => $user_array
        ];

        return $view_list;
    }

    public function actionRecord()
    {
        $view_var = $this->init_create();
        if (is_array($view_var)) {
            return $this->render('record', $view_var);
        }
    }

    /**
     * Creates a new Patient model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $view_var = $this->init_create();
        if (is_array($view_var)) {
            return $this->render('create', $view_var);
        }
    }


    private function get_modify_edit_string($model, $var)
    {
        $modify_string = "";
        $var_dict = Patientpower::get_var_instruction();

        foreach ($var as $key => $value) {
            if ($key != 'talk_log' && $model->$key != $value) {
                if ($key == 'disease_ids') {
                    $disease_old_name_array = [];
                    $disease_old_list = Disease::find()->where("id in ({$model->$key})")->all();
                    if (null != $disease_old_list && count($disease_old_list) > 0) {
                        foreach ($disease_old_list as $d) {
                            $disease_old_name_array[] = $d->name;
                        }
                    }
                    $model->$key = implode('.', $disease_old_name_array);
                    $disease_name_array = [];
                    $disease_list = Disease::find()->where("id in ({$value})")->all();
                    if (null != $disease_list && count($disease_list) > 0) {
                        foreach ($disease_list as $d) {
                            $disease_name_array[] = $d->name;
                        }
                    }
                    $value = implode('.', $disease_name_array);
                }

                $model->$key = $key == 'department_id' ? Department::findOne($model->$key)->name : $model->$key;
                $value = $key == 'department_id' ? Department::findOne($value)->name : $value;
                $model->$key = $key == 'comeway_id' ? Comeway::findOne($model->$key)->name : $model->$key;
                $value = $key == 'comeway_id' ? Comeway::findOne($value)->name : $value;
                $model->$key = $key == 'communication_id' ? Communication::findOne($model->$key)->name : $model->$key;
                $value = $key == 'communication_id' ? Communication::findOne($value)->name : $value;
                $model->$key = $key == 'order_doctor_id' ? Doctor::findOne($model->$key)->name : $model->$key;
                $value = $key == 'order_doctor_id' ? Doctor::findOne($value)->name : $value;
                $model->$key = $key == 'user_id' ? User::findOne($model->$key)->showname : $model->$key;
                $value = $key == 'user_id' ? User::findOne($value)->showname : $value;

                $modify_string .= '【' . $var_dict[$key] . '】 从 ' . $model->$key . ' 改为 ' . $value . ' <br />';
            }
        }

        return Yii::$app->user->identity->showname . " 于" . date('Y-m-d H:i:s') . '修改了患者的信息：<br />' . $modify_string . '---<br />';
    }



    private function init_update($id)
    {
        $model = $this->findModel($id);
        $var = Mytools::array_value_trim(Yii::$app->request->post('patient'));


        if (null != $var && count($var) > 0) {
            $model->edit_log .= $this->get_modify_edit_string($model, $var); //保存修改记录,必须放在最前面
            $model->user_id = $var['user_id'] ? $var['user_id'] : Yii::$app->user->getId();
            $var['istoday'] = $var['istoday'] == '是' ? '是' : '否';
            $model->name = $var['name'];
            $model->sex = $var['sex'];
            $model->telphone = $var['telphone'];
            $model->istoday = $var['istoday'];
            $model->workgroup = $var['workgroup'];
            $model->forever_id = $var['forever_id'];
            $model->order_time = $var['order_time'];
            $model->age = $var['age'];
            $model->order_number = $var['order_number'];
            $model->wechat = $var['wechat'];
            $model->qq = $var['qq'];
            $model->address = $var['address'];
            $model->keyword = $var['keyword'];
            $model->department_id = $var['department_id'];
            $model->disease_ids = $var['disease_ids'];
            $model->comeway_id = $var['comeway_id'];
            $model->communication_id = $var['communication_id'];
            $model->order_doctor_id = $var['order_doctor_id'];
            $model->condition_log = $var['condition_log'];
            $model->talk_log = $var['talk_log'];
            if ($model->order_number != $model->getOldAttribute('order_number')) {
                $model->status = '已改约';
            }


            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        $comeway_array = Comeway::getTreeData("status = '显示'", $model->comeway_id);
        $communication_array = Communication::getTreeData("status = '显示'", $model->communication_id);
        $department_array = Department::getTreeData("status = '显示'", $model->department_id);
        foreach ($department_array as $index => $d) {
            $department_array[$index]['disease_array'] = Disease::getTreeData("status = '显示' and id in ({$d['disease_ids']})", $model->disease_ids);
            $department_array[$index]['doctor_array'] = Doctor::getTreeData("status = '显示' and id in ({$d['doctor_ids']})", $model->order_doctor_id);
        }
        $workgroup_array = Workgroup::getTreeData('', $model->workgroup);
        $address_array = $this->get_address_tree($model->address);
        if (Patientpower::get_var_value('user_id') != '可修改' && Yii::$app->user->identity->jobname != '超级管理员') {
            $user_array = User::getTreeData("status = '在职'", $model->user_id, true);
        } else {
            $user_array = User::getTreeData("status = '在职'", $model->user_id);
        }

        return [
            'model' => $model,
            'comeway_array' => $comeway_array,
            'communication_array' => $communication_array,
            'department_array' => $department_array,
            'workgroup_array' => $workgroup_array,
            'address_array' => $address_array,
            'user_array' => $user_array
        ];
    }

    /**
     * Updates an existing Patient model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $view_var = $this->init_update($id);
        if (is_array($view_var)) {
            return $this->render('update', $view_var);
        }
    }

    public function actionEditrecord($id)
    {
        $view_var = $this->init_update($id);
        if (is_array($view_var)) {
            return $this->render('modify', $view_var);
        }
    }

    public function actionArrivedoctor($id)
    {
        $model = $this->findModel($id);
        $res['status'] = 'failure';
        $var = Yii::$app->request->post('patient');
        $model->arrive_time = date('Y-m-d H:i:s');
        $model->operate_doctor_id = $var['operate_doctor_id'];
        if ($model->save()) {
            $res['status'] = 'success';
        } else {
            $res['error'] = $model->getErrors();
        }
        echo json_encode($res);
    }

    public function actionRecordtoorder($id)
    {
        $model = $this->findModel($id);
        $res['status'] = 'failure';
        $var = Yii::$app->request->post('patient');
        $model->order_time = $var['order_time'];
        if ($model->save()) {
            $res['status'] = 'success';
        }
        echo json_encode($res);
    }


    /**
     * Deletes an existing Patient model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Patient model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Patient the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Patient::findOne($id)) !== null) {
            //权限控制，根据用户的患者信息表权限，确定哪些能看，哪些隐藏部分
            if (Yii::$app->user->identity->jobname != '超级管理员') {
                $job_id = Yii::$app->user->identity->job;
                $job = Job::find()->where("id = {$job_id}")->one();
                if (null != $job) {
                    $power_list = Patientpower::find()->where("id in ({$job->patient_powers})")->all();
                    foreach ($power_list as $p) {
                        if ($p->operate == '不显示') {
                            $patient_var_name = $p->var_name;
                            $model->$patient_var_name = null;
                        }
                    }
                }
            }
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }


    //验证姓名是否重复
    public function actionValidatename()
    {
        $res['status'] = 'failure';
        if (Yii::$app->request->isAjax) {
            $name = Yii::$app->request->get('name');
            $res['status'] = 'success';
            $patient_list = Patient::find()->where("name = '{$name}'")->all();
            if (null != $patient_list && count($patient_list) > 0) {
                foreach ($patient_list as $p) {
                    $res['data'][] = ['username' => $p->username, 'createtime' => $p->createtime, 'order_time' => $p->order_time, 'arrive_time' => $p->arrive_time];
                }
            }
        }

        echo json_encode($res);
    }

    //验证姓名是否重复
    public function actionValidatetelphone($number)
    {
        $res['status'] = 'failure';
        if (Yii::$app->request->isAjax) {
            $number = Yii::$app->request->get('number');
            $res['status'] = 'success';

            $patient_list = Patient::find()->where("telphone = '{$number}'")->all();
            if (null != $patient_list && count($patient_list) > 0) {
                foreach ($patient_list as $p) {
                    $res['data'][] = ['username' => $p->username, 'createtime' => $p->createtime, 'order_time' => $p->order_time, 'arrive_time' => $p->arrive_time];
                }
            }
        }

        echo json_encode($res);
    }

    //明日应到患者
    public function actionTomorrowarrive()
    {
        $search_condition_var = Yii::$app->request->get('search');

        $tomorrow = date('Y-m-d', strtotime('+1 days'));
        $where_default = "order_time like '{$tomorrow}%'" . " and department_id = " . Yii::$app->user->identity->department_id;
        $dataProvider = new ActiveDataProvider([
            'query' => $this->search($where_default, $search_condition_var),
        ]);

        return $this->render('index_tomorrow', [
            'dataProvider' => $dataProvider,
        ]);
    }

    //已过期患者。录单时间超过系统规定的7天，和预约时间过期的患者
    public function actionExpirydate()
    {
        $search_condition_var = Yii::$app->request->post('search');
        if (null == $search_condition_var || count($search_condition_var) < 1) {
            $search_condition_var = Yii::$app->request->get('search');
            if (null != $search_condition_var && count($search_condition_var) > 0) {
                foreach ($search_condition_var as $key => $value) {
                    switch ($value) {
                        case 'tomorrow':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('+1 day')) . ' - ' . date('Y-m-d', strtotime('+1 day'));
                            break;
                        case 'today':
                            $search_condition_var[$key] = date('Y-m-d') . ' - ' . date('Y-m-d');
                            break;
                        case 'yestoday':
                            $search_condition_var[$key] = date('Y-m-d', strtotime('-1 day')) . ' - ' . date('Y-m-d', strtotime('-1 day'));
                            break;
                    }
                }
            }
        }

        $workgroup_array = Workgroup::getTreeData('', $search_condition_var['workgroup']);
        $comeway_array = Comeway::getTreeData('', $search_condition_var['comeway_id']);
        $communication_array = Communication::getTreeData('', $search_condition_var['communication_id']);
        $disease_array = Disease::second_floor_key_value('', $search_condition_var['disease_ids']);
        $doctor_array = Doctor::getTreeData('', $search_condition_var['operate_doctor_id']);
        $status_array = ['未回访', '已回访', '确认到院', '已改约', '流失'];

        if (Patientpower::get_var_value('user_id') != '可修改' && Yii::$app->user->identity->jobname != '超级管理员') {
            $user_array = User::getTreeData("", Yii::$app->user->getId(), true);
        } else {
            $user_array = User::getTreeData();
        }

        $expirydate = date('Y-m-d H:i:s', strtotime('-' . Sysconfig::get_var_value('patient_record_expidy_date') . ' day'));
        $nowtime = date('Y-m-d H:i:s');
        if ($search_condition_var['expiry_type'] == 'record') {
            $where_default = "last_recall_time < '{$expirydate}' and order_time < '1999-01-01'";
        } else if ($search_condition_var['expiry_type'] == 'order_time') {
            $where_default = "order_time between '1999-01-01' and '{$nowtime}' and arrive_time < '1999-01-01'";
        } else {
            $where_default = "(last_recall_time < '{$expirydate}' and order_time < '1999-01-01') or (order_time between '1999-01-01' and '{$nowtime}' and arrive_time < '1999-01-01')";
        }
        $where_default = "(" . $where_default . ") and department_id = " . Yii::$app->user->identity->department_id;
        $dataProvider = new ActiveDataProvider([
            'query' => $this->search($where_default, $search_condition_var),
        ]);

        return $this->render('index_expirydate', [
            'dataProvider' => $dataProvider,
            'search' => $search_condition_var,
            'workgroup_array' => $workgroup_array,
            'comeway_array' => $comeway_array,
            'communication_array' => $communication_array,
            'user_array' => $user_array,
            'disease_array' => $disease_array,
            'doctor_array' => $doctor_array,
            'status_array' => $status_array
        ]);
    }

    //导出EXCEL
    public function actionExcelout()
    {
        $excel_start_time = Yii::$app->request->get('excel_start_time');
        $excel_end_time = Yii::$app->request->get('excel_end_time');
        $excel_type = Yii::$app->request->get('excel_type');

        //设置内存
        ini_set("memory_limit", "4096M");

        $objectPHPExcel = new \PHPExcel();
        $objectPHPExcel->getProperties()->setCreator('http://hospital.buy0851.com')
            ->setLastModifiedBy('http://hospital.buy0851.com')
            ->setTitle('Office 2007 XLSX Document')
            ->setSubject('Office 2007 XLSX Document')
            ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Result file');
        $objectPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '预约科室')
            ->setCellValue('B1', '预约号')
            ->setCellValue('C1', '姓名')
            ->setCellValue('D1', '年龄')
            ->setCellValue('E1', '性别')
            ->setCellValue('F1', '病种')
            ->setCellValue('G1', '现所属人')
            ->setCellValue('H1', '录单时间')
            ->setCellValue('I1', '预约时间')
            ->setCellValue('J1', '到诊时间')
            ->setCellValue('K1', '搜索关键词')
            ->setCellValue('L1', '永久身份')
            ->setCellValue('M1', '电话')
            ->setCellValue('N1', '所在地区')
            ->setCellValue('O1', '接诊医生')
            ->setCellValue('P1', '患者备注')
            ->setCellValue('Q1', '渠道来源');
        if (null != $excel_start_time && null != $excel_end_time && null != $excel_type) {
            $data = Patient::find()->where("{$excel_type} between '{$excel_start_time} 00:00:00' and '{$excel_end_time} 23:59:59'")->all(); //指定开始输出数据的行数
        }

        if ($data != null && count($data) > 0) {
            $i = 2;
            foreach ($data as $p) {
                $objectPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A' . $i, $p->department_name)
                    ->setCellValue('B' . $i, $p->order_number)
                    ->setCellValue('C' . $i, $p->name)
                    ->setCellValue('D' . $i, $p->age)
                    ->setCellValue('E' . $i, $p->sex)
                    ->setCellValue('F' . $i, $p->disease_name)
                    ->setCellValue('G' . $i, $p->username)
                    ->setCellValue('H' . $i, $p->createtime)
                    ->setCellValue('I' . $i, $p->order_time)
                    ->setCellValue('J' . $i, $p->arrive_time)
                    ->setCellValue('K' . $i, $p->keyword)
                    ->setCellValue('L' . $i, $p->forever_id)
                    ->setCellValue('M' . $i, $p->telphone)
                    ->setCellValue('N' . $i, $p->address)
                    ->setCellValue('O' . $i, $p->operate_doctor_name)
                    ->setCellValue('P' . $i, $p->condition_log)
                    ->setCellValue('Q' . $i, $p->comeway_name);

                $i++;
            }
        }
        $objectPHPExcel->getActiveSheet()->setTitle('友好数据表');
        $objectPHPExcel->setActiveSheetIndex(0);

        $objectPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(12);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(19);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(19);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(19);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(22);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(22);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(13);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(18);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(18);
        $objectPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(20);

        $filename = urlencode('导出数据') . '_' . date('Y-m-d H.i.s');

        //生成xls文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $writer->save('php://output');

        exit;
    }
}
